//import { UploadSignRes } from "./api/commonApi";
import commonStore from "../store/commonStore";
import api from "./api";
import config from "./config";

export const getOpenWxCode = (forceReauth = false) => {
	// 如果强制重新授权，清除缓存
	if (forceReauth) {
		setStorage('signCode', null)
		setStorage('authError', null)
	}
	
	//如果缓存中有code 说明已经获取过了
	const storageCode = getStorage('signCode') || {}
	if (storageCode.code && !forceReauth) {
		setStorage('signCode', null)
		return storageCode.code
	}
	
	// 检查URL参数
	const params : any = getUrlParams(window.location.href)
	
	// 检查是否有授权错误
	if (params.error) {
		alert('授权失败:'+params.error+params.error_description)
		setStorage('authError', {
			error: params.error,
			description: params.error_description || '用户拒绝授权'
		})
		return null
	}
	
	// 如果有code，保存并返回
	if (params.code) {
		setStorage('signCode', { code: params.code })
		setStorage('authError', null) // 清除之前的错误
		return params.code
	} 
	
	// 没有code且没有错误，跳转授权
	redirectToAuth()
	return null
}

// 跳转到授权页面
export const redirectToAuth = () => {
	let str = 'https://open.weixin.qq.com/connect/oauth2/authorize'
	str += '?appid=' + config.wxOpenId
	str += '&redirect_uri=' + encodeURIComponent(window.location.origin+'/h5/#/pages/public/wxcode')
	str += '&response_type=code&scope=snsapi_privateinfo'
	str += `&agentid=${config.agentId}#wechat_redirect`
	window.location.href = str
}

// 检查是否有授权错误
export const getAuthError = () => {
	return getStorage('authError')
}

// 清除授权错误
export const clearAuthError = () => {
	setStorage('authError', null)
}
export const format = (timeStr : string | number | Date, type = "yyyy-MM-dd hh:mm:ss") => {
	if (!timeStr) return "/";
	// let validTime : any = ''
	// if (typeof timeStr === 'string') {
	// 	validTime = timeStr.replace(/-/g, '/')
	// } else {
	// 	validTime = timeStr
	// }
	const time = new Date(timeStr);
	if (!time) return "/";
	const y = time.getFullYear();
	const m = time.getMonth() + 1;
	const d = time.getDate();
	const h = time.getHours();
	const mm = time.getMinutes();
	const s = time.getSeconds();
	const add0 = (m : number) : string => {
		return m < 10 ? "0" + m : m + "";
	};
	switch (type) {
		case "minDay":
			return y + "/" + add0(m) + "/" + "01";
		default:
			return type
				.replace("yyyy", y + "")
				.replace("MM", add0(m))
				.replace("dd", add0(d))
				.replace("hh", add0(h))
				.replace("mm", add0(mm))
				.replace("ss", add0(s));
	}
};
export const isNumberInt = (value : string | number) => {
	const reg = /^-?[0-9]+?$/
	return reg.test(value + '')
}
export const isNumber = (value : string | number) => {
	const reg = /^-?[0-9]+(\.[0-9]+)?$/
	return reg.test(value + '')
}
export const isPhone = (value : string | number) => {
	const reg = /^1[3-9]\d{9}$/
	return reg.test(value + '')
}
export const toDecimalStr = (num, len = 2) => {
	const fixedNum = num.toFixed(len);
	return fixedNum
}
export const toDecimalNum = (num, len = 2) => {
	const fixedNum = num.toFixed(len);
	return Number(fixedNum)
}
// num：要转换的数字，x: 保留x 为小数，x 需大于0
export const toDecimalNoZero = (num: number, x: number = 2) => {
    const b = Math.pow(10, x)
    var f = Math.round(num * b) / b
    var s = f.toString()
    return s
}
let GLOBAL_LOADING_NUM = 0
export const editLoadingNum = () => {
	GLOBAL_LOADING_NUM = 0
}
export const showLoading = (params ?: { title ?: string; mask ?: boolean }) => {
	let defParams = {
		title: "加载中...",
		mask: true,
	};
	defParams = { ...defParams, ...params };
	GLOBAL_LOADING_NUM++
	uni.showLoading(defParams);
};
export const hideLoading = () => {
	GLOBAL_LOADING_NUM--
	if (GLOBAL_LOADING_NUM <= 0) uni.hideLoading();
};
interface ToastParmas {
	title ?: string;
	icon ?: "none" | "success" | "loading";
	mask ?: boolean;
	duration ?: number;
}
export const showToast = (title : string, params ?: ToastParmas, callback ?: () => void) => {
	let defParams : any = {
		title: title,
		icon: "none",
		mask: true,
		duration: 1500,
	}
	defParams = { ...defParams, ...params };
	setTimeout(() => {
		uni.showToast(defParams);
		if (callback) {
			setTimeout(callback, defParams.duration);
		}
	}, 10)

}

/**
 *
 * @param {string} item storage的名称
 * @param {type} type 可以传，默认session，接受local和session
 */
export const getStorage = (item : string) => {
	let data;
	data = uni.getStorageSync(item);
	if (data) {
		try {
			data = JSON.parse(data);
		} catch (err) {
			data = data || null;
		}
		return data;
	}
	return null;
};
/**
 *
 * @param name Storage key
 * @param value Storage value
 * @param type session||local
 */
export const setStorage = (name : string, value : any) => {
	uni.setStorageSync(name, JSON.stringify(value))
};
export const goBack = (num : number = 1) => {
	let back = getCurrentPages()
	if (back && back.length > 1) {
		uni.navigateBack({
			delta: num
		})
	} else {
		if (num === 1) {
			history.back()
		} else {
			history.go(-1 * num)
		}
	}
}
export const chooseImage = (callback, count = 1, maxLen = 10) => {
	const maxbit = maxLen * 1024 * 1024
	uni.chooseImage({
		count: count,
		sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
		sourceType: ['album'], //从相册选择
		success: function (res) {
			if (res.tempFiles[0] && res.tempFiles[0].size > maxbit) {
				showToast(`图片不能超过${maxLen}m，请重新选择`)
				return
			}
			callback && callback(res)
		}
	});
}
export const getGuid = () => {
	const S4 = function () {
		return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
	};
	return (S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4())
}
export const lookImage = (current : number, urls : string[], w = 700) => {
	const resizeUrls = urls.map(item => {
		return resizeImg(item, w)
	})
	// 预览图片
	uni.previewImage({
		current,
		urls: resizeUrls,
		longPressActions: {
			itemList: ['发送给朋友', '保存图片', '收藏'],
			success: function (data) {
				console.log('选中了第' + (data.tapIndex + 1) + '个按钮,第' + (data.index + 1) + '张图片');
			},
			fail: function (err) {
				console.log(err.errMsg);
			}
		}
	});
}
export const resizeImg = (url : string, w = 200, water = true) => {
	let returnUrl = url
	if (!url) return url
	if (url.indexOf(config.ossFileUrl) >= 0) {
		returnUrl = returnUrl + `?x-oss-process=image/resize,w_${w}`
		if (w >= 500 && water) {
			returnUrl += '/watermark,text_5Ymn54Sx54Sx,t_70,color_888888,size_30'
		}
	}
	return returnUrl


}
export const chooseVideo = (callback) => {
	uni.chooseVideo({
		sourceType: ['camera', 'album'],
		extension: ['mp4', 'webm', 'ogg', 'mpeg4'],
		success: function (res) {
			callback && callback(res)
		}
	});
}
export const hidePhone = (phoneNumber : string) => {
	if(!phoneNumber) return''
	const hiddenPhoneNumber = phoneNumber.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
	return hiddenPhoneNumber
}
export const getUrlParams = (url : string) => {
	const paramsRegex = /[?&]+([^=&]+)=([^&]*)/gi;
	const params = {};
	let match;
	while (match = paramsRegex.exec(url)) {
		params[match[1]] = match[2];
	}
	return params;
}
export const getSmallWxCode = (callback) => {
	// 如果没有code，跳转获取code
	wx.login({
		success: (res) => {
			if (res.code) {
				callback(res.code)
			} else {
				console.log('登录失败！' + res.errMsg)
			}
		}
	})

}

export const isWechat = () => {
	if (!window) return false
	if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(window.navigator.userAgent)) {

	} else {
		return false
	}

	var ua = window.navigator.userAgent.toLowerCase();
	if (ua.match(/micromessenger/i) == 'micromessenger') {
		//console.log('是微信客户端')  
		return true;
	} else {
		//console.log('不是微信客户端')  
		return false;
	}
}

export const getValidNum = (num : string | number, len = 2) => {
	const nums = num + ''
	const n = Number(num) || 0
	if (nums.indexOf('w') > 0 || nums.indexOf('W') > 0 || nums.indexOf('万') > 0) {
		return toLocaleString(n) + 'W'
	}
	if (n > 10000) {
		return toLocaleString(Number((n / 10000).toFixed(len))) + 'W'
	} else {
		return toLocaleString(Number(n.toFixed(len)))
	}
}
export const toLocaleString = (num : string | number) => {
	return num.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,');
	// var p = n.replace(r, "$1,")
	// return Number(num).toLocaleString()
}

export const getLastDayOfMonth = (date : Date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1; // 月份从0开始，需要加1
	const lastDateOfMonth = new Date(year, month, 0);
	return lastDateOfMonth;
}
export const getStartDayOfMonth = (date : Date) => {
	const year = date.getFullYear();
	const month = date.getMonth(); // 月份从0开始，需要加1
	const startDateOfMonth = new Date(year, month, 1);
	return startDateOfMonth;
}
export const isIosWx = () => {
	const info = uni.getSystemInfoSync()
	if (info.platform === 'ios') {
		return true
	}
	return false
}
export const getUserInfo = async () => {
	const res =await api.getUserInfo()
	setStorage("userInfo", res.user);
}

export const uploadFile = (filePath : any) => {
	let userAuth = getStorage('userAuth') || {}
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: config.apiUrl + '/file/uploadImage',
			filePath: filePath,
			name: 'file',
			formData: {},
			header: { authorization: userAuth.token || '' },
			success: (uploadFileRes) => {
				resolve(uploadFileRes)
			},
			fail: (res) => {
				console.info(res)
				showToast('图片上传失败')
				reject()
			}
		});
	})

}
export const utilLogin = () => {
	let userAuth = getStorage('userAuth') || {}

	if (userAuth && userAuth.token) {
		return true
	} else {
		uni.showModal({
			title: '提示',
			content: '您还没有登录，请登录后重试。',
			confirmText: '立即登录',
			success: (res) => {
				if (res.confirm) {
					uni.navigateTo({ url: '/pages/login/index' })
				} else if (res.cancel) {
					console.log('用户点击取消');
				}
			}
		});
		return false
	}

}

/**
 * 截取字符串前N位
 * @param text 
 * @param maxLength 
 * @returns 
 */
export const truncateText = (text, maxLength = 20) => {
    if (text.length > maxLength) {
        return text.substring(0, maxLength) + '...';
    }
    return text;
}

export const toYuan = (num) => {
	return num ? toDecimalNum(num / 100) : 0
}
export const handleImageError = (data,key) => {
	data[key]=config.fileUrl+'empty.png'
}
